package it.fuesi.synotools.fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

import it.fuesi.synotools.R;
import it.fuesi.synotools.activities.DownloadStationSettingsActivity;
import it.fuesi.synotools.activities.DownloadTaskDetailActivity;
import it.fuesi.synotools.activities.MainActivity;
import it.fuesi.synotools.activities.base.ADetailActivity;
import it.fuesi.synotools.adapters.DownloadTasksAdapter;
import it.fuesi.synotools.helpers.FormatHelper;
import it.fuesi.synotools.model.download.DownloadStationClientParameters;
import it.fuesi.synotools.model.download.DownloadTask;
import it.fuesi.synotools.services.tasks.download.ClearCompletedTask;
import it.fuesi.synotools.services.tasks.download.CreateDownloadTask;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link DownloadStationFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link DownloadStationFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class DownloadStationFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SECTION_NUMBER = "section_number";


    // TODO: Rename and change types of parameters
    private int mSectionNumber;

    private OnFragmentInteractionListener mListener;

    private ListView mTasks;
    private DownloadTasksAdapter mAdapter;



    @Override
    public void onActionRefresh() {
        mAdapter.fetch(DownloadStationClientParameters.build(true));
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     *
     * @return A new instance of fragment DownloadStationFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DownloadStationFragment newInstance(int position) {
        DownloadStationFragment fragment = new DownloadStationFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, position);
        fragment.setArguments(args);
        return fragment;
    }
    public DownloadStationFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
        }



    }

    private TextView mTotal;
    private TextView mCompleted;
    private TextView mPending;

    private TextView mDownloadSpeedTorrent;
    private TextView mDownloadSpeedEmule;


    @Override
    public boolean onBackPressed() {
        final MainActivity main = (MainActivity)getActivity();
        main.quit();
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        final View rootView = inflater.inflate(R.layout.fragment_download_station, container, false);

        mTasks = (ListView)rootView.findViewById(R.id.download_tasks);

        mAdapter = new DownloadTasksAdapter(inflater,null, this.getActivity(), this);

        mTasks.setAdapter(mAdapter);

        mTotal = (TextView)rootView.findViewById(R.id.download_status_total);
        mCompleted = (TextView)rootView.findViewById(R.id.download_status_completed);
        mPending = (TextView)rootView.findViewById(R.id.download_status_pending);

        mDownloadSpeedTorrent = (TextView)rootView.findViewById(R.id.download_speed_torrent);
        mDownloadSpeedEmule = (TextView)rootView.findViewById(R.id.download_speed_emule);


        mAdapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();

                mTasks.scrollTo(0,0);

                mTotal.setText(""+mAdapter.getTotal());
                mCompleted.setText(""+mAdapter.getCompleted());
                mPending.setText(""+mAdapter.getPending());


                mDownloadSpeedTorrent.setText(FormatHelper.formatSpeed(mAdapter.getInfo().getSpeed_download()));
                mDownloadSpeedEmule.setText(FormatHelper.formatSpeed(mAdapter.getInfo().getEmule_speed_download()));


            }
        });

        mTasks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                DownloadTask task = (DownloadTask)mAdapter.getItem(i);
                Intent intent = new Intent(getActivity(), DownloadTaskDetailActivity.class);
                intent.putExtra(ADetailActivity.EXTRA_DETAIL_ITEM, task);
                startActivityForResult(intent, DownloadTaskDetailActivity.REQUEST_CODE);
            }
        });


        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();

        mAdapter.fetch();
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;

        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }

            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_add) {
            askForUrl();
            return true;
        }else if(id == R.id.action_clear_completed){
            clearCompleted();
            return true;
        }else if(id == R.id.action_download_config){
            openDownloadConfig();
            return true;
        }

        return false;
    }


    private void openDownloadConfig(){
        Intent i = new Intent(getActivity(), DownloadStationSettingsActivity.class);
        startActivity(i); //FIXME: maybe startActivityForResult
    }

    private EditText mNewUrl;

    private void askForUrl(){
        mNewUrl = new EditText(getActivity());

        new AlertDialog.Builder(getActivity())
                .setTitle(getString(R.string.new_download_confirm_title))
                .setMessage(getString(R.string.new_download_uri_confirm_message))
                .setView(mNewUrl)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        final String url = mNewUrl.getText().toString();
                        Log.d("DownloadStationFragment", "Adding url: " + url );
                        addDownloadTask(url);

                    }
                })
                .setIcon(android.R.drawable.ic_dialog_email)
                .show();
    }

    private void addDownloadTask(String url){
        DownloadStationClientParameters params = new DownloadStationClientParameters();
        params.setUri(url);
        new CreateDownloadTask(getActivity()).execute(params);
    }

    private void clearCompleted(){
        List<DownloadTask> completed = mAdapter.getCompletedTasks();
        DownloadStationClientParameters params = new DownloadStationClientParameters();
        params.setTasks(completed);
        new ClearCompletedTask(getActivity()).execute(params);

    }



}
